// pages/games/slot/slot.js
Page({
  data: {
    userPoints: 100,
    isSpinning: false,
    currentReels: [
      { icon: '🍒', rarity: 'common' },
      { icon: '🍋', rarity: 'common' },
      { icon: '🍊', rarity: 'common' }
    ],
    slideStates: ['', '', ''], // 动画状态类名
    lastWin: 0,
    showWinLine: false,
    showNoPointsModal: false,
    showWinModal: false,
    isDarkMode: false,
    
    // 老虎机图标池
    icons: [
      { icon: '🍒', rarity: 'common', weight: 30 },
      { icon: '🍋', rarity: 'common', weight: 25 },
      { icon: '🍊', rarity: 'common', weight: 20 },
      { icon: '🍇', rarity: 'rare', weight: 10 },
      { icon: '🍓', rarity: 'rare', weight: 8 },
      { icon: '🔔', rarity: 'epic', weight: 4 },
      { icon: '💎', rarity: 'legendary', weight: 2 },
      { icon: '7️⃣', rarity: 'legendary', weight: 1 }
    ],
    
    // 奖励规则
    rewards: [
      { pattern: '🍒🍒🍒', prize: 10 },
      { pattern: '🍋🍋🍋', prize: 15 },
      { pattern: '🍊🍊🍊', prize: 20 },
      { pattern: '🍇🍇🍇', prize: 30 },
      { pattern: '🍓🍓🍓', prize: 50 },
      { pattern: '🔔🔔🔔', prize: 100 },
      { pattern: '💎💎💎', prize: 200 },
      { pattern: '7️⃣7️⃣7️⃣', prize: 500 },
      { pattern: '任意三个相同', prize: 5 }
    ]
  },

  onLoad() {
    this.loadUserData();
    this.checkDarkMode();
  },

  onShow() {
    this.loadUserData();
  },

  // 加载用户数据 - 统一使用games/index的积分
  loadUserData() {
    const userData = wx.getStorageSync('userData') || {};
    this.setData({
      userPoints: userData.points || 100
    });
  },

  // 保存用户数据 - 保存到统一的userData
  saveUserData() {
    const userData = wx.getStorageSync('userData') || {};
    userData.points = this.data.userPoints;
    wx.setStorageSync('userData', userData);
  },

  // 检查深色模式
  checkDarkMode() {
    const systemInfo = wx.getSystemInfoSync();
    this.setData({
      isDarkMode: systemInfo.theme === 'dark'
    });
  },

  // 根据权重随机选择图标
  getRandomIcon() {
    const totalWeight = this.data.icons.reduce((sum, icon) => sum + icon.weight, 0);
    let random = Math.random() * totalWeight;
    
    for (let icon of this.data.icons) {
      random -= icon.weight;
      if (random <= 0) {
        return icon;
      }
    }
    
    return this.data.icons[0];
  },

  // 旋转老虎机
  spinSlots() {
    if (this.data.isSpinning || this.data.userPoints < 2) {
      if (this.data.userPoints < 2) {
        this.setData({ showNoPointsModal: true });
      }
      return;
    }

    // 扣除积分
    this.setData({
      userPoints: this.data.userPoints - 2,
      isSpinning: true,
      showWinLine: false,
      lastWin: 0
    });
    this.saveUserData();

    // 重置动画状态并启动旋转
    this.setData({
      slideStates: ['', '', '']
    }, () => {
      // 确保状态重置后再开始动画
      setTimeout(() => {
        this.spinAnimation();
      }, 50);
    });
  },

  // 优化后的滑动动画 - 从上往下滑
  spinAnimation() {
    // 使用requestAnimationFrame优化性能，避免卡屏
    this.setData({
      isSpinning: true
    });
    
    // 预加载图标序列，避免运行时计算
    const iconPool = [];
    for (let i = 0; i < 30; i++) {
      iconPool.push(this.getRandomIcon());
    }
    
    // 每个滚轴的动画配置 - 调整步数和时长让动画更自然
    const reelConfigs = [
      { index: 0, duration: 1000, delay: 0, steps: 12 },
      { index: 1, duration: 1400, delay: 200, steps: 15 },
      { index: 2, duration: 1800, delay: 400, steps: 18 }
    ];
    
    // 启动每个滚轴的动画
    reelConfigs.forEach(config => {
      this.animateReelWithSlide(config, iconPool);
    });
    
    // 设置最终停止时间 - 调整为新的总时长
    setTimeout(() => {
      this.stopSpin();
    }, 2200);
  },

  // 优化的滚轴动画 - 变速滑动效果
  animateReelWithSlide(config, iconPool) {
    const { index, duration, delay, steps } = config;
    
    setTimeout(() => {
      let currentStep = 0;
      
      const animateStep = () => {
        if (currentStep < steps) {
          // 计算动态延迟：开始快，逐渐变慢
          const progress = currentStep / steps;
          const easeOut = 1 - Math.pow(1 - progress, 3); // 缓出效果
          const dynamicDelay = 50 + (400 * easeOut); // 从50ms逐渐增加到450ms
          
          // 滑出动画 - 加速版
          this.setData({
            [`slideStates[${index}]`]: 'up-out-fast'
          });
          
          setTimeout(() => {
            // 更新图标
            const newReels = [...this.data.currentReels];
            const iconIndex = (index * steps) + currentStep;
            newReels[index] = iconPool[iconIndex % iconPool.length];
            
            // 滑入动画 - 根据步骤调整速度
            const slideInType = currentStep === steps - 1 ? 'down-in-final' : 'down-in-fast';
            this.setData({
              currentReels: newReels,
              [`slideStates[${index}]`]: slideInType
            });
            
            currentStep++;
            
            if (currentStep < steps) {
              // 重置状态继续下一轮
              setTimeout(() => {
                this.setData({
                  [`slideStates[${index}]`]: ''
                });
                setTimeout(animateStep, 50);
              }, 200);
            } else {
              // 最终停止 - 添加完成提醒
              setTimeout(() => {
                this.setData({
                  [`slideStates[${index}]`]: ''
                });
                
                // 如果是最后一个滚轴完成，显示完成提醒
                if (index === 2) {
                  this.showResultNotification();
                }
              }, 300);
            }
          }, 150); // 快速滑出
        }
      };
      
      animateStep();
    }, delay);
  },

  // 辅助函数：使用requestAnimationFrame
  requestAnimationFrame(callback) {
    setTimeout(callback, 16); // 约60fps
  },

  // 停止旋转并计算结果
  stopSpin() {
    // 最终随机结果
    const finalReels = [
      this.getRandomIcon(),
      this.getRandomIcon(),
      this.getRandomIcon()
    ];

    this.setData({
      currentReels: finalReels,
      isSpinning: false
    });

    // 计算中奖
    this.calculateWin(finalReels);
  },

  // 计算中奖结果
  calculateWin(reels) {
    const icons = reels.map(reel => reel.icon);
    const pattern = icons.join('');
    let winAmount = 0;

    // 检查特殊组合
    for (let reward of this.data.rewards) {
      if (reward.pattern === pattern) {
        winAmount = reward.prize;
        break;
      }
    }

    // 检查任意三个相同
    if (winAmount === 0 && icons[0] === icons[1] && icons[1] === icons[2]) {
      winAmount = 5;
    }

    if (winAmount > 0) {
      // 中奖动画和奖励
      this.setData({
        lastWin: winAmount,
        showWinLine: true,
        userPoints: this.data.userPoints + winAmount
      });
      this.saveUserData();

      // 添加中奖图标高亮效果
      setTimeout(() => {
        this.setData({ showWinModal: true });
      }, 800); // 延迟增加，让用户看到中奖线效果
    }

    // 5秒后隐藏中奖线（延长显示时间）
    setTimeout(() => {
      this.setData({ showWinLine: false });
    }, 5000);
  },

  // 显示结果提醒
  showResultNotification() {
    // 震动反馈（如果支持）
    if (wx.vibrateShort) {
      wx.vibrateShort();
    }
    
    // 计算最终是否中奖
    const reels = this.data.currentReels;
    const icons = reels.map(reel => reel.icon);
    const pattern = icons.join('');
    let hasWon = false;
    
    // 检查是否中奖
    for (let reward of this.data.rewards) {
      if (reward.pattern === pattern) {
        hasWon = true;
        break;
      }
    }
    
    if (!hasWon && icons[0] === icons[1] && icons[1] === icons[2]) {
      hasWon = true;
    }
    
    // 显示结果提醒
    if (hasWon) {
      // 中奖提醒
      wx.showToast({
        title: '🎉 恭喜中奖！',
        icon: 'success',
        duration: 2000,
        mask: true
      });
    } else {
      // 未中奖提醒
      wx.showToast({
        title: '😊 再试一次',
        icon: 'none',
        duration: 1500,
        mask: true
      });
    }
  },

  // 关闭积分不足弹窗
  closeNoPointsModal() {
    this.setData({ showNoPointsModal: false });
  },

  // 关闭中奖弹窗
  closeWinModal() {
    this.setData({ showWinModal: false });
  },

  // 防止事件冒泡
  preventClose() {
    // 空函数，用于阻止事件冒泡
  },

  // 分享功能
  onShareAppMessage() {
    return {
      title: '来玩幸运老虎机！看看你的手气如何',
      path: '/pages/games/slot/slot',
      imageUrl: '/assets/images/slot-share.jpg'
    };
  }
});